package myJs.cps

import cats.effect.{IO, SyncIO}
import myJs.myPkg.reactHookForm._
import japgolly.scalajs.react._
import myJs.myPkg.Hooks._
import japgolly.scalajs.react.vdom.all._

import scala.scalajs.js
import myJs.Implicits._
import myJs.myPkg.reactBootstrap._
import myJs.tool.Tool.messages

/** Created by yz on 3/11/2020
  */
object TextareaInlineCp {

  case class Props(
      name: String,
      registerOptions: RegisterOptions = RegisterOptions(),
      onChange: String => SyncIO[Unit],
      value: String,
      label: String,
      labelWidth: Int = 2,
      inputWidth: Int = 4,
      readOnly: Boolean = false,
      showExample: SyncIO[Unit] = SyncIO {},
      hasExample: Boolean = true,
      show: Boolean = true,
      questionInfo: String = ""
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val formState = ReactHookForm.useFormState(options =
      UseFormStateOptions(
        name = props.name
      )
    )
    object FTool {}

    val hasErrorCls = if (formState.errors.isDefinedAt(props.name)) "has-error" else ""
    val displayStr = if (props.show) "block" else "none"
    div(
      display := displayStr,
      className := s"form-group ${hasErrorCls}",
      label(
        className := s"control-label col-sm-${props.labelWidth}",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          {
            val popover = Popover(id = "popover-basic")(
              Popover.Header(messages("note")),
              Popover.Body(
                props.questionInfo
              )
            ).rawElement
            OverlayTrigger(
              placement = "auto",
              trigger = js.Array("hover", "focus"),
              overlay = popover
            )(
              span(
                a(`type` := "button", i(className := "fa fa-question-circle-o"))
              )
            )
          }
        } else EmptyVdom,
        ":"
      ),
      div(
        className := s"col-sm-${props.inputWidth}",
        PureTextareaCp
          .Props(
            name = props.name,
            onChange = props.onChange,
            value = props.value
          )
          .render,
        if (props.hasExample) {
          span(className := "help-block", a(onClick --> props.showExample, em("示例")))
        } else EmptyVdom
      )
    )

  }

}
